/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.tnmk.worktime.service.dao;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.tnmk.worktime.service.dao.entry.BaseEntry;

/**
 * This class simulate the table in DBMS
 * @author tnmkhoi
 */
public class DataTable<E extends BaseEntry> {
  private final Map<Integer, E> entriesMap = new HashMap<>();
  private volatile int nextId = 0;

  protected void addData(List<E> list){
    for (E e : list) {
      autoSetId(e);
      entriesMap.put(e.getId(), e);
    }
  }

  protected void autoSetId(E e) {
    Integer id = e.getId();
    if (id == null) {
      e.setId(nextId);
    }
    if (e.getId() >= nextId) {
      nextId = e.getId() + 1;
    }
  }

  protected void autoSetIds(List<E> list) {
    for (E e : list) {
      autoSetId(e);
    }
  }
  /**
   * Add or update
   * @param e 
   */
  public void set(E e) {
    autoSetId(e);
    entriesMap.put(e.getId(), e);
  }
  /**
   * @param id
   * @return return old element
   */
  public E remove(Integer id){
    if (id == null) {
      return null;
    }    
    return entriesMap.remove(id);
  }
  public E select(Integer id){
    if (id == null) {
      return null;
    }
    return entriesMap.get(id);
  }
  /**
   * @return a list which is not reference to data in storage
   */
  public List<E> selectAll(){
    List<E> rs = new ArrayList<>();
    rs.addAll(entriesMap.values());
    return rs;
  }
  protected Collection<E> values(){
    return entriesMap.values();
  }
}
